#include "sysupdate.h"
#include "ui_sysupdate.h"
#include <QFileDialog>
#include <QMessageBox>
#include <sys/types.h>
#include <sys/stat.h>
#include "msgbox.h"
#include <unistd.h>
#include "udiskupgrade.h"
#include "loading.h"
#include "versionchoose.h"
#include "powermanager.h"
#include "userlogger.h"

SysUpdate::SysUpdate(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SysUpdate)
{
    ui->setupUi(this);

    bdf = BllDataFlow::getInstance();
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &SysUpdate::retranslateUiSlot);

    m_upgradeMgr = new UdiskUpgrade(this);
    connect(m_upgradeMgr, SIGNAL(done(const QString &, bool)), this, SLOT(onDone(const QString &, bool)));
    connect(m_upgradeMgr, SIGNAL(done(const QStringList &)), this, SLOT(onDone(const QStringList &)));

    initWidget();
}

SysUpdate::~SysUpdate()
{
    delete ui;
}

void SysUpdate::on_btnEnumUpgradePackage_clicked()
{
    Loading::showLoading(QColor(0,0,0,200), false, tr("Detect..."));
    UserLogger::log(tr("Detect Upgrade Package"));
    m_upgradeMgr->enumUpgradePackages();
}

void SysUpdate::on_btnUpgrade_clicked()
{
    Loading::showLoading(QColor(0,0,0,200), false, tr("Upgrading..."));
    UserLogger::log(QString("%1: %2").arg(tr("Upgrade")).arg(ui->lblSelectedFile->text()));
    m_upgradeMgr->upgrade(ui->lblSelectedFile->text());
}

void SysUpdate::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void SysUpdate::onDone(const QString &info, bool restart)
{
    UserLogger::log(info);
    MsgBox::information(this, tr("Upgrade"), info);
    if (restart)
    {
        PowerManager::restart();
    }

    Loading::hideLoading();
}

void SysUpdate::onDone(const QStringList &files)
{
    if (files.isEmpty())
    {
        QString message = tr("No version detected.");
        UserLogger::log(message);
        ui->btnUpgrade->setEnabled(false);
        MsgBox::information(this, tr("Upgrade"), message);
    }
    else
    {
        UserLogger::log(QString("%1: \n%2").arg(tr("Following Upgrade Package")).arg(files.join(", ")));

        VersionChoose dlg;
        QString packageName = dlg.show(files);
        ui->lblSelectedFile->setText(packageName);
        ui->btnUpgrade->setEnabled(true);
    }

    Loading::hideLoading();
}

void SysUpdate::initWidget()
{
    ui->btnUpgrade->setEnabled(false);
}
